import { FC, useEffect, useState } from 'react';
import { Form, Input, Button, message, Checkbox } from 'antd';
import request from 'umi-request';

import { useHistory } from 'umi';

import './index.less';

/*
  登录请求：'http://pudge.wang:3000/api/users/login'， post
    参数
      - username
      - password

  admin 123456
  zhangsan 123
*/

const Login: FC = () => {
  const [form] = Form.useForm();
  const history = useHistory();
  // const [obj, set_obj] = useState({});

  useEffect(() => {
    if (localStorage.getItem('remember')) {
      form.setFieldsValue({
        username: localStorage.getItem('username'),
        password: localStorage.getItem('password'),
        remember: localStorage.getItem('remember'),
      });
    }
  }, []);

  const onFinish = (values: any) => {
    const { username, password, remember } = values;
    request
      .post('http://pudge.wang:3000/api/users/login', {
        data: {
          username,
          password,
        },
      })
      .then((res) => {
        if (res.status === 0) {
          if (remember) {
            localStorage.setItem('username', username);
            localStorage.setItem('password', password);
            localStorage.setItem('remember', remember);
          } else {
            localStorage.clear();
          }

          sessionStorage.setItem('auth', JSON.stringify(res.result[0].auth));
          message.success('登录成功');
          history.push('/admin/welcome');
        } else {
          message.warning(res.msg);
        }
      })
      .catch((error) => {
        message.error(error.message);
      });
  };
  return (
    <div className="login">
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        autoComplete="off"
        form={form}
        // 用于设置form的初始值
        // initialValues={obj}
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[{ required: true, message: 'Please input your username!' }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[{ required: true, message: 'Please input your password!' }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          name="remember"
          valuePropName="checked"
          wrapperCol={{ offset: 8, span: 16 }}
        >
          <Checkbox>Remember me</Checkbox>
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            Submit
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
